package com.javawork.juc.five;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhangxiaolu
 * @since 2023-02-12 16:02
 */
public class AtomicIntegerDemo {

    public static final int SIZE = 50;

    public static void main(String[] args) throws InterruptedException {
        MyNumber myNumber = new MyNumber();
        CountDownLatch countDownLatch = new CountDownLatch(SIZE);
        for (int i = 0; i < SIZE; i++) {
            new Thread(() -> {
                try {
                    for (int j = 0; j <1000; j++) {
                        myNumber.addNumber();
                    }
                } finally {
                    countDownLatch.countDown();
                }
            }, String.valueOf(i)).start();
        }

        countDownLatch.await();
//        try {
//            TimeUnit.SECONDS.sleep(2);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        System.out.println(Thread.currentThread().getName() + "\t result :" + myNumber.atomicInteger.get());
    }
}

class MyNumber {

    AtomicInteger atomicInteger = new AtomicInteger();

    public void addNumber() {
        atomicInteger.getAndIncrement();//相当于++
    }
}